import React from 'react';
import {Row,Col,Button,Input,Modal,message} from 'antd';
import styles from  './styles.less';
const { TextArea } = Input;

let socket = io(window.location.origin);

const getDate = () => {
    let _targetDate = new Date();
    const Y = _targetDate.getFullYear();
    const M = _targetDate.getMonth()>8?(_targetDate.getMonth()*1+1):('0' + (_targetDate.getMonth()*1+1));
    const D = _targetDate.getDate()>9?_targetDate.getDate():('0' + _targetDate.getDate());
    const h = _targetDate.getHours()>9?_targetDate.getHours():('0' + _targetDate.getHours());
    const m = _targetDate.getMinutes()>9?_targetDate.getMinutes():('0' + _targetDate.getMinutes());
    const s = _targetDate.getSeconds()>9?_targetDate.getSeconds():('0' + _targetDate.getSeconds());
    return `${Y}-${M}-${D} ${h}:${m}:${s}`;
}
export default class Main extends React.Component {
	constructor(props){
		super(props);
		this.state = {
            showLogin:true,
            hideMsg:false,
			...props
		}
		this.handleButtonClick = this.handleButtonClick.bind(this);
		this.login = this.login.bind(this);
	}
    handleButtonClick(){
	    console.log(this.refs);
	    const msgVal = this.refs.textarea.textAreaRef;
	    if(msgVal.value){
	        const socket = this.state.socket;
	        const msg = {
	            key:new Date().getTime() + this.state.userName,
	            type:'msg',
                value:msgVal.value,
                from:this.state.userName,
                date:getDate()
	        };
            socket.emit('send',msg);
            msg.from = 'SELF';
            let msgList = this.state.msgList?this.state.msgList:[];
            msgList.push(msg);
            this.setState({
                msgList:msgList
            });
            msgVal.value = '';
        }
    }
    login(){
        const socket = this.state.socket;
        if(socket){
            const userName = this.refs.userName.refs.input.value;
            if(userName){
                socket.emit('login',userName);
                this.setState({
                    showLogin:false,
                    userName:userName
                });
            }
        }else{
            message.error('对不起,没连接到服务器.......😞',10);
        }

    }
    componentDidMount(){
        const that = this;
        socket.on('msg',function (msg) {
            console.log('get msg',msg);
            if(msg && msg.message){
                const msgList = that.state.msgList?that.state.msgList:[];
                msgList.push(msg.message);
                that.setState({
                    msgList:msgList
                });
            }
        });
        socket.on('online',function (msg) {
            console.log('online',msg);
            if(msg.username){
                message.warning(msg.username+'上线啦 (y*~*y)',2);
            }
            that.setState({
                numOnlineUsers: msg.numUsers
            });
        });
        socket.on('offline',function (msg) {
            console.log('offline',msg);
            if(msg.username) {
                message.warning(msg.username + "已下线 (|||-'_'-) ", 2);
            }
            that.setState({
                numOnlineUsers: msg.numUsers
            });
        });
        socket.on('errors',function (msg) {
            console.log('errors',msg);
            message.error(msg.infos,2);
            if(msg.code==2001){
                that.setState({
                    showLogin:true,
                    userName:''
                });
            }
        });
        this.setState({
            socket:socket
        });
    }
	render(){
        const leftColStyle = {
            xs:{span:18},
            sm:{span:18},
            md:{span:15,offset:2}
        };
        const rightColStyle = {
            xs:{span:6},
            sm:{span:6},
            md:{span:5}
        };
		return (
            <div>
                <div>
                    <Row gutter={24} style={{height:'35px',lineHeight:'35px',marginTop:'10px'}}>
                        <Col {...leftColStyle}>
                            <h1>匿名聊天{this.state.userName?` - ${this.state.userName}`:''}</h1>
                        </Col>
                        <Col {...rightColStyle} style={{textAlign:'center'}}>
                            <h1>聊天组</h1>
                        </Col>
                    </Row>
                    <Row gutter={24}>
                        <Col {...leftColStyle} className={styles.chatZoom} >
                            <div className={styles.chatList}>
                            {this.state.msgList?this.state.msgList.map((ele,index)=>{
                                if(ele.type === 'img'){

                                }else{
                                    const SELF = (ele.from === 'SELF');
                                    return (
                                        <div className={SELF?styles.chatSubSelf:styles.chatSub} key={index}>
                                            <div className={styles.chatFrom}>
                                                {SELF?'你各个儿':ele.from}说：
                                            </div>
                                            <div className={styles.chatPopo}>
                                                {ele.value}
                                            </div>
                                            <div className={styles.chatDate}>
                                                {ele.date}
                                            </div>
                                        </div>
                                    );
                                }
                            }):''}
                            </div>
                        </Col>
                        <Col {...rightColStyle} style={{textAlign:'center'}}>
                            <div className={styles.groupTab}>
                                全部
                                <span>(在线{this.state.numOnlineUsers?this.state.numOnlineUsers:0}人)</span>
                            </div>
                        </Col>
                    </Row>
                    <Row gutter={24} style={{marginTop:'20px',display:this.state.hideMsg?'none':'static'}}>
                        <Col {...leftColStyle}>
                            <TextArea ref="textarea" maxLength={1000} placeholder="你要发点儿啥？"/>
                        </Col>
                        <Col {...rightColStyle} style={{paddingLeft:'20px',paddingTop:'10px'}}>
                            <Button onClick={this.handleButtonClick} type="primary">发送</Button>
                        </Col>
                    </Row>

                </div>
                <Modal
                    title="登录"
                    closable={false}
                    maskClosable={false}
                    visible={this.state.showLogin}
                    onOk={this.login}
                    onCancel={()=>{this.setState({hideMsg:true,showLogin:false})}}
                    okText="登录"
                    cancelText="取消"
                >
                    <Input maxLength={20} placeholder="尊姓大名？" ref="userName" type="text" />
                </Modal>
            </div>
			);
	}
}